package cn.gan.loveofsoul.service.impl;

import cn.gan.loveofsoul.commons.result.ErrorMessage;
import cn.gan.loveofsoul.commons.result.Result;
import cn.gan.loveofsoul.commons.result.StatusCode;
import cn.gan.loveofsoul.entity.CommemorateDay;
import cn.gan.loveofsoul.entity.Relationship;
import cn.gan.loveofsoul.entity.User;
import cn.gan.loveofsoul.exception.BusinessException;
import cn.gan.loveofsoul.mapper.CommemorateDayMapper;
import cn.gan.loveofsoul.service.ICommemorateDayService;
import cn.gan.loveofsoul.service.IRelationshipService;
import cn.gan.loveofsoul.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ganwh
 * @since 2023-10-26
 */
@Service
public class CommemorateDayServiceImpl extends ServiceImpl<CommemorateDayMapper, CommemorateDay> implements ICommemorateDayService {
    @Autowired
    private IRelationshipService relationshipService;
    @Autowired
    private IUserService userService;

    public Result queryUserCommemorateDayInfo(Integer userId) {
        Relationship relationship = relationshipService.queryUserRelationship(userId);
        if (Objects.isNull(relationship)) {
            throw new BusinessException(StatusCode.NOT_FOUND, ErrorMessage.HAS_NO_RELATIONSHIP);
        }

        LambdaQueryWrapper<CommemorateDay> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CommemorateDay::getRelationshipId, relationship.getId());
        wrapper.orderByAsc(CommemorateDay::getOrder);
        List<CommemorateDay> commemorateDayList = list(wrapper);
        commemorateDayList.forEach(commemorateDay -> {
            if (Objects.nonNull(commemorateDay.getUserId())) {
                Optional<User> userOptional = userService.getOptById(commemorateDay.getUserId());
                userOptional.orElseThrow(() -> new BusinessException(StatusCode.NOT_FOUND, ErrorMessage.USER_NOT_EXIST));
                commemorateDay.setRemark(userOptional.get().getUserName() + commemorateDay.getRemark());
            }
        });
        return new Result(StatusCode.SUCCESS, ErrorMessage.SUCCESS, commemorateDayList);
    }
}
